/**
 * 两个数字用链表倒序表示，返回两个数字相加的结果。
 * 举例：463表示为：3->6->4，154表示为：4->5->1
 * 两数相加结果 617表示为： 7->1->6
 * 链表每个节点上只能有一位数字
 */

function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}


function addTwoNodeNum(l1, l2) {
    const dummy = new ListNode(0);
    let current = dummy;
    let carry = 0;
    while(l1 || l2) {
        const curSum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
        const newNode = new ListNode(curSum % 10);
        current.next = newNode;
        carry = Math.floor(curSum/ 10);
        l1 = l1?.next ?? null;
        l2 = l2?.next ?? null;
        current = newNode;
    }
    if (carry > 0) {
        current.next = new ListNode(carry);
    }
    return dummy.next;
}

const l1 = new ListNode(9, new ListNode(9, new ListNode(9)));
const l2 = new ListNode(9, new ListNode(9));
console.log(addTwoNodeNum(l1, l2));
